import torch

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

w = torch.tensor([1.0])  # w的初值为1.0
w.requires_grad = True  # 需要计算梯度

def forward(x):
    return x * w  # w是一个Tensor

def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) ** 2

print("predict (before training)", 4, forward(4).item(), '\n') #Tensor.item()只会返回一个元素的Tensor

for epoch in range(10):
    for x, y in zip(x_data, y_data):
        l = loss(x, y)
        l.backward()  # 反向传播
        print('\tgrad:', x, y, w.grad.item())
        print(w.grad.data, type(w.grad.data))
        print(w, type(w), '\n')
        w.data = w.data - 0.01 * w.grad.data

        w.grad.data.zero_()  # 更新后，梯度清零

    print('progress:', epoch, l.item(), type(l), '\n')

print("predict (after training)", 4, forward(4).item())